package com.company.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;

/**
 * @ClassName DataSourceConfiguration
 * @Description
 */
/* 加载配置文件 <context:property-placeholder location="classpath:jdbc.properties"/> */
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
    /*
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
*/
//    @Bean("dataSource")
//    public DataSource getDataSource() throws SQLException {
//        // 1. 读取配置文件
//        ResourceBundle resource = ResourceBundle.getBundle("jdbc");
//        // 2. 创建数据源对象
//        DruidDataSource dataSource = new DruidDataSource();
//        dataSource.setDriverClassName(resource.getString("jdbc.driver"));   // 1. 设置驱动
//        dataSource.setUrl(resource.getString("jdbc.url"));                  // 2. 设置数据库路径
//        dataSource.setUsername(resource.getString("jdbc.username"));
//        dataSource.setPassword(resource.getString("jdbc.password"));
//
//        // 3. 获取资源并进行操作
//        Connection connection = dataSource.getConnection();
//        System.out.println(connection);
//
//        // 4. 关闭，将资源归还到连接池中
//        connection.close();
//        return null;
//    }

    @Bean("dataSource")
    public DataSource getDataSource() throws SQLException {
        // 1. 读取配置文件
        ResourceBundle resource = ResourceBundle.getBundle("jdbc");
        // 2. 创建数据源对象
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(resource.getString("jdbc.driver"));   // 1. 设置驱动
        dataSource.setUrl(resource.getString("jdbc.url"));                  // 2. 设置数据库路径
        dataSource.setUsername(resource.getString("jdbc.username"));
        dataSource.setPassword(resource.getString("jdbc.password"));

        // 3. 获取资源并进行操作
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        // 4. 关闭，将资源归还到连接池中
        connection.close();
        return null;
    }
}
